package com.moji.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.RoleMenuRel;
import com.moji.entity.SysMenu;
import com.moji.entity.SysRole;
import com.moji.entity.SysUser;
import com.moji.entity.dto.AddRoleMenuRelDto;
import com.moji.entity.dto.PrOnOffDto;
import com.moji.entity.dto.RoleSelectBoxDto;
import com.moji.entity.dto.TreeDto;
import com.moji.enums.MoJiEnumConfig;
import com.moji.mapper.SysRoleMapper;
import com.moji.service.RoleMenuRelService;
import com.moji.service.SysMenuService;
import com.moji.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.service.SysUserService;
import com.moji.util.MoJiCommonUtils;
import com.moji.util.RoleTreeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-07-23
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private RoleMenuRelService roleMenuRelService;

    @Override
    public boolean add(SysRole record) {
        //所属部门不能为空
        if(org.apache.commons.lang3.StringUtils.isEmpty(record.getDeptCode())){
            //throw new RuntimeException("所属部门不能为空,请核查!");
        }
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SysRole::getRoleCode);
        List<SysRole> roleList = this.list(wrapper);
        if(!roleList.isEmpty()){
            String roleCode = String.format("%06d",Integer.parseInt(roleList.get(0).getRoleCode())+1);
            record.setRoleCode(roleCode);
        }else{
            String roleCode = String.format("%06d",1);
            record.setRoleCode(roleCode);
        }
        record.setPrOnoff(Integer.parseInt(MoJiEnumConfig.CCP_SYSTEM_PR_ON_OFF.getCode()));
        record.setOrderNo(ObjectUtil.isEmpty(record.getOrderNo())?1:record.getOrderNo());
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        record.setUpdateId(MoJiCommonUtils.getUserCode());
        record.setCreateId(MoJiCommonUtils.getUserCode());
        this.save(record);

        //保存权限
        List<String> list=record.getList();
        if(ObjectUtil.isNotEmpty(list)){
            LambdaQueryWrapper<SysMenu> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.in(SysMenu::getMenuCode,list);
            List<SysMenu> sysMenuList=sysMenuService.list(wrapper1);
            sysMenuList.forEach(item->{
                RoleMenuRel roleMenuRel=new RoleMenuRel();
                BeanUtil.copyProperties(item,roleMenuRel);
                roleMenuRel.setRoleCode(record.getRoleCode());
                roleMenuRel.setRoleName(record.getRoleName());
                roleMenuRel.setCreateTime(new Date());
                roleMenuRel.setUpdateTime(new Date());
                roleMenuRel.setMenuFlag(item.getMenuFlag());
                roleMenuRel.setUpdateId(MoJiCommonUtils.getUserCode());
                roleMenuRel.setCreateId(MoJiCommonUtils.getUserCode());
                roleMenuRelService.save(roleMenuRel);
            });
        }
        return true;
    }

    @Override
    public boolean edit(SysRole sysRole) {
        SysRole sysRole1=this.getById(sysRole.getId());
        if(sysRole1==null){
            throw new RuntimeException("角色不存在,请核查!");
        }
        BeanUtil.copyProperties(sysRole,sysRole1);
        sysRole1.setUpdateTime(new Date());
        sysRole1.setUpdateId(MoJiCommonUtils.getUserCode());
        this.updateById(sysRole1);
        //保存权限
        List<String> list=sysRole.getList();
        if(ObjectUtil.isNotEmpty(list)){
            //删除原来的
            roleMenuRelService.remove(new LambdaQueryWrapper<RoleMenuRel>()
                    .in(RoleMenuRel::getRoleCode,sysRole.getRoleCode()));
            //新增
            LambdaQueryWrapper<SysMenu> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.in(SysMenu::getMenuCode,list);
            List<SysMenu> sysMenuList=sysMenuService.list(wrapper1);
            sysMenuList.forEach(item->{
                RoleMenuRel roleMenuRel=new RoleMenuRel();
                BeanUtil.copyProperties(item,roleMenuRel);
                roleMenuRel.setRoleCode(sysRole1.getRoleCode());
                roleMenuRel.setRoleName(sysRole1.getRoleName());
                roleMenuRel.setCreateTime(new Date());
                roleMenuRel.setUpdateTime(new Date());
                roleMenuRel.setUpdateId(MoJiCommonUtils.getUserCode());
                roleMenuRel.setCreateId(MoJiCommonUtils.getUserCode());
                roleMenuRelService.save(roleMenuRel);
            });
        }
        return true;
    }

    @Override
    public boolean delete(Long id) {
        SysRole sysRole=this.getById(id);
        if(sysRole==null){
            throw new RuntimeException("角色不存在,请核查!");
        }
        roleMenuRelService.remove(new LambdaQueryWrapper<RoleMenuRel>()
                .eq(RoleMenuRel::getRoleCode,sysRole.getRoleCode()));
        return this.removeById(id);
    }

    @Override
    public MyPage<SysRole> queryPage(SysRole ccpSystemRole) {
        LambdaQueryWrapper<SysRole> ccpSystemRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(ccpSystemRole.getRoleName())){
            ccpSystemRoleLambdaQueryWrapper.like(SysRole::getRoleName,ccpSystemRole.getRoleName());
        }
        if(StringUtils.isNotEmpty(ccpSystemRole.getRoleCode())){
            ccpSystemRoleLambdaQueryWrapper.like(SysRole::getRoleCode,ccpSystemRole.getRoleCode());
        }
        if(StringUtils.isNotEmpty(ccpSystemRole.getDeptCode())){
            ccpSystemRoleLambdaQueryWrapper.eq(SysRole::getDeptCode,ccpSystemRole.getDeptCode());
        }
        ccpSystemRoleLambdaQueryWrapper.orderByDesc(SysRole::getOrderNo);
        PageHelper.startPage(ccpSystemRole.getPageNum(), ccpSystemRole.getPageSize());
        List<SysRole> roleList = this.list(ccpSystemRoleLambdaQueryWrapper);
        PageInfo<SysRole> info = new PageInfo<>(roleList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public List<RoleSelectBoxDto> queryRoleSelectBox() {
        List<RoleSelectBoxDto> roleSelectBoxlist = new ArrayList<>();
        LambdaQueryWrapper<SysRole> ccpSystemRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<SysRole> roleList = this.list(ccpSystemRoleLambdaQueryWrapper);
        RoleSelectBoxDto roleSelectBoxDao = null;
        if(!roleList.isEmpty()){
            for (SysRole ccpSystemRole : roleList){
                roleSelectBoxDao = new RoleSelectBoxDto();
                roleSelectBoxDao.setRolesCode(ccpSystemRole.getRoleCode());
                roleSelectBoxDao.setRoleName(ccpSystemRole.getRoleName());
                roleSelectBoxlist.add(roleSelectBoxDao);
            }
        }
        return roleSelectBoxlist;
    }

    @Override
    public List<TreeDto> queryRoleTree() {
        LambdaQueryWrapper<SysRole> ccpSystemRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<SysRole> roleList = this.list(ccpSystemRoleLambdaQueryWrapper);
        return RoleTreeUtil.list2Tree(roleList);
    }

    @Override
    public boolean updateRoleStatus(PrOnOffDto prOnOffDao) {
        SysRole sysRole = this.getById(prOnOffDao.getId());
        if(sysRole != null){
            sysRole.setPrOnoff(Integer.parseInt(prOnOffDao.getPrOnOff()));
            sysRole.setPrOnoffTime(new Date());
        }
        return this.updateById(sysRole);
    }

    @Override
    public Set<String> queryRoleAuth(String roleCode) {
        Set<String> set =new HashSet<>();
        if(ObjectUtil.isEmpty(roleCode)){
            throw new RuntimeException("角色编码为空,请核查!");
        }
        List<String> roles= Arrays.asList(roleCode.split(","));
        LambdaQueryWrapper<RoleMenuRel> wrapper=new LambdaQueryWrapper<>();
        wrapper.in(RoleMenuRel::getRoleCode,roles);
        List<RoleMenuRel> roleMenuRels=roleMenuRelService.list(wrapper);
        if(ObjectUtil.isNotEmpty(roleMenuRels)){
            roleMenuRels.forEach(item->{
                set.add(item.getMenuCode());
            });
        }
        return set;
    }
}
